/**
 * 
 */
package com.servicecloud.filter;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * 
 *
 * @author Gavin<br>
 * 可以统一处理拦截器中的所有异常
 *         2020年4月10日
 */
@Component
public class ErrorZuulFilter extends ZuulFilter {

	/* 
	 */
	@Override
	public boolean shouldFilter() {
		// TODO Auto-generated method stub
		return RequestContext.getCurrentContext().containsKey("throwable");
	}

	/* 
	 */
	@Override
	public Object run() {
		try {
			System.err.println(2);
			RequestContext ctx = RequestContext.getCurrentContext();
			Object e = ctx.get("throwable");
			if (e != null && e instanceof RuntimeException) {
				RuntimeException zuulException = (RuntimeException) e; // Remove error code to prevent further error
																		// handling in follow up filters
				// 删除该异常信息,不然在下一个过滤器中还会被执行处理
				ctx.remove("throwable"); // 根据具体的业务逻辑来处理
				ctx.setResponseStatusCode(501);
				ctx.setResponseBody("访问人太多了，请先等一哈儿。");
			}
		} catch (Exception ex) {
			ReflectionUtils.rethrowRuntimeException(ex);
		}
		return null;
	}

	/* 
	 */
	@Override
	public String filterType() {
		return FilterConstants.ERROR_TYPE;
	}

	/* 
	 */
	@Override
	public int filterOrder() {
		// TODO Auto-generated method stub
		return FilterConstants.SEND_ERROR_FILTER_ORDER-1;
	}

}
